// pages/borrowManage/borrowManage.js
Page({
    data: {
      applicant: '', // 领用人输入框的值
      records: [],   // 查询结果
      applicationDate: '',
    },
  
    onApplicantInput(e) {
      this.setData({ applicant: e.detail.value }); // 更新输入框值
    },
  
    async handleSearch() {
      const { applicant } = this.data; // 获取输入框值
  
      const app = getApp();
      const db = app.globalData.db;
  
      // 构建查询条件
      let query = {};
      if (applicant.trim()) {
        query = {
          applicant: db.RegExp({ regexp: applicant, options: 'i' }), // 忽略大小写的模糊匹配
        };
      }
  
      console.log('查询条件：', query);
  
      try {
        // 查询数据库
        const res = await db.collection('records').where(query).get();
        const records = res.data;
  
        // 获取每条记录的当前库存
        for (const record of records) {
          for (const item of record.items) {
            const stockRes = await db.collection('items')
              .where({ materialNumber: item.materialNumber })
              .get();
            item.currentStock = stockRes.data[0]?.quantity || 0; // 当前库存
          }
        }
  
        this.setData({ records });

        this.setData({
             applicationDate:this.formatDate(records[0].applicationDate),
        });

        //console.log('records记录有:',records[0].applicationDate);


        if (records.length === 0) {
          wx.showToast({ title: '未找到相关记录', icon: 'none' });
        }
      } catch (err) {
        wx.showToast({ title: '查询失败，请稍后重试', icon: 'none' });
        console.error('查询错误：', err);
      }
    },

    // rejectRecord(e) {
    //   const recordId = e.currentTarget.dataset.recordId;
    //   const app = getApp(); // 获取小程序实例
    //   const cloud = app.globalData.cloud; // 获取云开发实例
    //   wx.showModal({
    //     title: '确认拒绝',
    //     content: '确定要拒绝这条领用记录吗？',
    //     success: async (res) => {
    //       if (res.confirm) {
    //         try {
    //           await cloud.callFunction({
    //             name: 'rejectRecord',
    //             data: { recordId },
    //           });
  
    //           wx.showToast({ title: '拒绝成功', icon: 'success' });
    //           this.handleSearch(); // 刷新列表
    //         } catch (err) {
    //           wx.showToast({ title: '拒绝失败，请稍后重试', icon: 'none' });
    //           console.error(err);
    //         }
    //       }
    //     },
    //   });
    // },
    
    rejectRecord(e) {
        const recordId = e.currentTarget.dataset.recordId;
        const app = getApp(); // 获取小程序实例
        const cloud = app.globalData.cloud; // 获取云开发实例
        wx.showModal({
          title: '确认拒绝',
          content: '确定要拒绝这条领用记录吗？',
          success: async (res) => {
            if (res.confirm) {
              try {
                await cloud.callFunction({
                  name: 'rejectRecord', // 调用拒绝云函数
                  data: { recordId },
                });
      
                wx.showToast({ title: '拒绝成功!!!', icon: 'success' });
                this.handleSearch(); // 刷新列表
              } catch (err) {
                wx.showToast({ title: '拒绝失败，请稍后重试', icon: 'none' });
                console.error(err);
              }
            }
          },
        });
      },

    approveRecord(e) {
        const recordId = e.currentTarget.dataset.recordId;
        const app = getApp(); // 获取小程序实例
        const cloud = app.globalData.cloud; // 获取云开发实例
        wx.showModal({
          title: '确认批准',
          content: '确定要批准这条领用记录吗？',
          success: async (res) => {
            if (res.confirm) {
              try {
                const result = await cloud.callFunction({
                  name: 'approveRecord',
                  data: { recordId },
                });
    
                if (result.result.success) {
                  wx.showToast({ title: result.result.message, icon: 'success' });
                  this.handleSearch(); // 刷新记录列表
                } else {
                  wx.showToast({ title: result.result.message, icon: 'none' });
                }
              } catch (err) {
                wx.showToast({ title: '操作失败，请稍后重试!!', icon: 'none' });
                console.error(err);
              }
            }
          },
        });
      },


    revokeRecord(e) {
        const recordId = e.currentTarget.dataset.recordId;
        const app = getApp(); // 获取小程序实例
        const cloud = app.globalData.cloud; // 获取云开发实例
       
        // const itemId = e.currentTarget.dataset.itemId;
        // console.log('recordId1:', recordId);

        // const item = e.currentTarget.dataset;
        // console.log('record:', item);

        wx.showModal({
          title: '确认撤回',
          content: '确定要撤回这条领用记录的状态吗？',
          success: async (res) => {
            if (res.confirm) {
              try {
                // 查询当前记录的详细信息
                const { result: record } = await cloud.callFunction({
                  name: 'getRecordDetails',
                  data: { recordId },
                });
      
                if (!record || record.status !== 'approved') {
                  wx.showToast({ title: '无法撤回该记录', icon: 'none' });
                  return;
                }
                
                
                 console.log('record是:', record.items);
                // 更新库存并删除记录
                await cloud.callFunction({
                  name: 'updateStockAndDeleteRecord',
                  data: {
                    recordId,
                    item: record.items,
                    //newQuantity,
                  },
                });
      
                wx.showToast({ title: '撤回成功', icon: 'success' });
                this.handleSearch(); // 刷新列表
              } catch (err) {
                wx.showToast({ title: '!!!撤回失败，请稍后重试', icon: 'none' });
                console.error(err);
              }
            }
          },
        });
    },
  


    formatDate(dateString) {
        console.log('传入的日期字符串:', dateString); // 添加调试日志
        if (!dateString) return ''; // 如果日期为空，返回空字符串
      
        let date;
        try {
          date = new Date(dateString);
          if (isNaN(date.getTime())) {
            console.error('无效的日期格式:', dateString);
            return '';
          }
        } catch (err) {
          console.error('日期解析失败:', err);
          return '';
        }
      
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },  

    onLoad() {
      // 页面加载时，默认显示全部记录
      this.handleSearch();
    },
  });